﻿//+--------------------------------------------------------------------------------------------------------------------------------------------------------
//     
//Description: DeployWizardViewModel
//Author: Aravind Ramarathinam (aravr@microsoft.com)
//Copyright © Microsoft Corporation
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
//You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
//THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
//INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 
//See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
// 
//--------------------------------------------------------------------------------------------------------------------------------------------------------


using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Text;
using System.Diagnostics;
using System.Windows.Input;

using VmroleAuthor.Commands;
using VmroleAuthor.Models;

namespace VmroleAuthor.ViewModels
{
    public class DeployViewModel : ViewModelBase
    {
        private readonly ObservableCollection<DeployPageViewModelBase> wizardPagesViewModels;
        private readonly ResExtAzureDeploymentData deployData;
        private readonly VmRoleResourceExtensionViewModel resExtViewModel;


        private readonly DeployLandingPageViewModel landingPageViewModel;
        private readonly DeploySettingsPageViewModel settingsPageViewModel;
        private readonly DeployResultsPageViewModel resultsPageViewModel;

        public DeployViewModel(VmRoleResourceExtensionViewModel resExtViewModel, Window deployWindow)
        {
            this.wizardPagesViewModels = new ObservableCollection<DeployPageViewModelBase>();
            this.deployData = new ResExtAzureDeploymentData();
            this.resExtViewModel = resExtViewModel;

            this.landingPageViewModel = new DeployLandingPageViewModel(this.resExtViewModel, this.deployData);
            this.settingsPageViewModel = new DeploySettingsPageViewModel(this.resExtViewModel, this.deployData);
            this.resultsPageViewModel = new DeployResultsPageViewModel(this.resExtViewModel, this.deployData, deployWindow);
            this.InitPageVMs();
        }

        private void InitPageVMs()
        {            
            this.wizardPagesViewModels.Add(this.landingPageViewModel );
            this.wizardPagesViewModels.Add(this.settingsPageViewModel);
            this.wizardPagesViewModels.Add(this.resultsPageViewModel);
            this.NextPageCommand = new RelayCommand(param => this.NextPage(), param => this.CanGoToNextPage());
            this.BackPageCommand = new RelayCommand(param => this.BackPage(), param => this.CanGoToBackPage());
            this.SettingsCommand = new RelayCommand(param => this.OpenSettings(), param => this.CanOpenSettings());
            this.PowerShellScriptCommand = new RelayCommand(param => this.OpenPowerShellScript(), param => this.CanOpenPowerShellScript());
        }

        public DeployPageViewModelBase CurrentDeployPage
        {
            get
            {
                return this.wizardPagesViewModels[currentDeploymentPageIndex];
            }
        }

        public string ResExtName
        {
            get
            {
                return this.resExtViewModel.Name;
            }
        }

        public string ResExtVersion
        {
            get
            {
                return this.resExtViewModel.Version;
            }
        }

        public string ResExtPublisher
        {
            get
            {
                return this.resExtViewModel.Publisher;
            }
        }

        public string PageTitle
        {
            get
            {
                return this.CurrentDeployPage.PageTitle;
            }
        }

        public string ResExtService
        {
            get
            {
                if (this.deployData.SelectedCloudService != null)
                {
                    return this.deployData.SelectedCloudService.Name;
                }
                return string.Empty;
            }
        }

        public string ResExtVM
        {
            get
            {
                if (this.deployData.SelectedVirtualMachine != null)
                {
                    return this.deployData.SelectedVirtualMachine.Name;
                }
                return string.Empty;
            }
        }

        public string NextButtonSource
        {
            get
            {
                switch(this.currentDeploymentPageIndex)
                {
                    case 0:
                        return "..\\Img\\next_34.png";
                    default:
                        return "..\\Img\\complete_34.png";
                }
            }
        }

        public string NextButtonToolTip
        {
            get
            {
                switch (this.currentDeploymentPageIndex)
                {
                    case 1:
                        return "Deploy resource extension button";
                    case 2:
                        return "Close wizard button";
                    default:
                        return  "Next page button";
                }
            }
        }

        public object BackButtonVisibility
        {
            get
            {
                return ((this.currentDeploymentPageIndex <= 0 || this.currentDeploymentPageIndex >= 2) ? Visibility.Hidden : Visibility.Visible);
            }
        }

        public object NextButtonVisibility
        {
            get
            {
                return ((this.currentDeploymentPageIndex >= 3) ? Visibility.Hidden : Visibility.Visible);
            }
        }

        public object ConfigVisibility
        {
            get
            {
                return ((this.currentDeploymentPageIndex >= 1) ? Visibility.Visible : Visibility.Hidden);
            }
        }

        public object AltButtonVisibility
        {
            get
            {
                return ((this.currentDeploymentPageIndex >= 1) ? Visibility.Visible : Visibility.Hidden);
            }
        }

        private int currentDeploymentPageIndex;
        private int CurrentDeploymentPageIndex
        {
            get
            {
                return this.currentDeploymentPageIndex;
            }
            set
            {
                this.currentDeploymentPageIndex = value;
                this.OnPropertyChanged("CurrentDeployPage");
                this.OnPropertyChanged("BackButtonVisibility");
                this.OnPropertyChanged("NextButtonVisibility");
                this.OnPropertyChanged("NextButtonSource");
                this.OnPropertyChanged("ResExtName");
                this.OnPropertyChanged("ResExtVersion");
                this.OnPropertyChanged("ResExtPublisher");
                this.OnPropertyChanged("ConfigVisibility");
                this.OnPropertyChanged("ResExtService");
                this.OnPropertyChanged("ResExtVM");
                this.OnPropertyChanged("PageTitle");
                this.OnPropertyChanged("AltButtonVisibility");
                this.OnPropertyChanged("NextButtonToolTip");
            }
        }

        public ICommand BackPageCommand
        {
            get;
            private set;
        }

        public bool CanGoToBackPage()
        {
            return (this.CurrentDeploymentPageIndex > 0);
        }

        private void BackPage()
        {
            if (this.CurrentDeploymentPageIndex > 0)
            {
                this.CurrentDeploymentPageIndex -= 1;
            }
        }

        public ICommand NextPageCommand
        {
            get;
            private set;
        }

        public bool CanGoToNextPage()
        {
            return (this.CurrentDeploymentPageIndex < 3) && this.CurrentDeployPage.IsUserInputComplete;
        }

        private void NextPage()
        {
            if (this.CurrentDeploymentPageIndex < this.wizardPagesViewModels.Count - 1)
            {
                if (this.CurrentDeployPage.PerformNextStep())
                {
                    this.CurrentDeploymentPageIndex += 1;
                }
            }
            else if (this.CurrentDeploymentPageIndex == this.wizardPagesViewModels.Count - 1)
            {
                this.CurrentDeployPage.PerformNextStep();
            }
        }

        public ICommand SettingsCommand
        {
            get;
            private set;
        }

        public bool CanOpenSettings()
        {
            return ((this.currentDeploymentPageIndex == 1 && this.CurrentDeployPage.IsUserInputComplete) || 
                (this.currentDeploymentPageIndex > 1));
        }

        private void OpenSettings()
        {
            string fName = System.IO.Path.GetTempFileName() + ".txt";

            // write to the temp file
            FileStream fStream = new FileStream(fName, FileMode.Append);
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(JsonHelper.PrettyPrentJson(this.CurrentDeployPage.GetSettings()));
                fStream.Write(bytes, 0, bytes.Length);
            }
            finally
            {
                fStream.Close();
            }
            // open the temp file
            Process.Start(fName);
        }

        public ICommand PowerShellScriptCommand
        {
            get;
            private set;
        }

        public bool CanOpenPowerShellScript()
        {
            return ((this.currentDeploymentPageIndex == 1 && this.CurrentDeployPage.IsUserInputComplete) ||
                (this.currentDeploymentPageIndex > 1));
        }

        private void OpenPowerShellScript()
        {
            string fName = System.IO.Path.GetTempFileName() + ".txt";

            // write to the temp file
            FileStream fStream = new FileStream(fName, FileMode.Append);
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(this.CurrentDeployPage.GetPowerShellScript());
                fStream.Write(bytes, 0, bytes.Length);
            }
            finally
            {
                fStream.Close();
            }
            // open the temp file
            Process.Start(fName);
        }
    }
}
